<template>
    <div class="app-view">
        <vxe-grid id="xGrid"
                  :loading="tableLoading"
                  ref="xGrid"
                  border
                  resizable
                  show-overflow
                  keep-source
                  highlight-hover-row
                  :height="tableH"
                  align="center"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  :custom-config="{ storage: true }"
                  :toolbar-config="tableToolbar"
                  :columns="tableColumn"
                  :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize,}"
                  :pager-config="tablePage"
                  :data="tableData"
                  @page-change="handlePageChange"
                  @checkbox-change="checkboxChange"
                  @checkbox-all="checkboxAll">
            <template #projectName="{ row }">
                <div class="tableTxt tableTxtHoverBlue" @click="show">
                    <div class="textHidden">{{ row.name }}</div>
                </div>
            </template>
            <template v-slot:toolbar_buttons>
                <div class="tableToolbar">
                    <div style="min-width:90px" class="tableToolbarText tableToolbarTextL">数据包名称：</div>
                    <el-input v-model="searchName" size="small" style="margin-inline-start:8px;width:50%;" :placeholder="placeholder"
                              clearable @clear="getData(0)" @change="getData(0)" />
                    <vxe-button style="min-width:55px;margin-left:8px" status="primary" size="small" class="tableToolbarTextL searchButton"
                                @click="getData(0)">查询</vxe-button>
                    <vxe-button style="min-width: 55px; margin-left: 8px" status="primary" class="tableToolbarTextL addButton" size="small"
                                @click="save">导出</vxe-button>

                </div>
            </template>
            <template #operate="{ row }">
                <el-link type="primary" class="elLinkBTN" @click="downloadFile(row)">下载</el-link>
                <el-link type="danger" class="elLinkBTN" @click="deleteDe(row)">删除</el-link>
            </template>
            <template v-slot:current_pageNum>
            </template>
        </vxe-grid>

        <vxe-modal v-model="showCreate" :title="formTitle" width="500" resize destroy-on-close @close="dialogFormClose">
            <template #default>
                <vxe-form title-colon ref="myform" :data="formInfo" :items="formItems" :rules="formRules">
                    <template #planStartTime="{ data }">
                        <vxe-input v-model="data.startTime" placeholder="请选择计划开始时间" transfer type="date" labelFormat="yyyy-MM-dd" :disabled-method="disabledPlanStartTime" />
                    </template>
                    <template #planEndTime="{ data }">
                        <vxe-input v-model="data.endTime" placeholder="请选择计划结束时间" transfer type="date" labelFormat="yyyy-MM-dd" :disabled-method="disabledPlanEndTime" />
                    </template>
                </vxe-form>
                <div style="text-align:right">
                    <el-button @click="dialogFormClose">取 消</el-button>
                    <el-button type="primary" @click="save" class="searchButton">确 定</el-button>
                </div>
            </template>
        </vxe-modal>
    </div>
</template>
<script>
    import dataExportAPI from "../../request/DataManage/DataExportAPI.js";
    import prjAPI from '../../request/Project/PrjAPI.js';
    export default {
        components: {
        },
        name: 'GZFX',
        data() {
            return {
                tableData: [],
                treeLoading: false,
                tableH: window.innerHeight - topBarHeight - 80,
                searchHolder: '请输入',
                expandKeysArr: [1, 2, 3, 4, 5, 6, 7],
                selectTree: null,
                activeName: null,
                numName: null,
                tableLoading: false,
                searchName: null,
                placeholder: "请输入",
                selectedItems: [],
                allPrjList:[],
                tableColumn: [
                    { type: "seq", title: "序号", width: 70, fixed: "left" },
                    //{ field: "prjID", minWidth: 120, title: "关联项目", minWidth: 200, formatter: ({ row }) => { return this.format(this.allPrjList, row.prjID) } },
                    { field: "fileName", minWidth: 130, title: "数据包名称", fixed: 'left', },
                    { field: "exportTime", minWidth: 100, title: "导出时间", fixed: 'left', },
                    { title: "操作", fixed: "right", width: 120, slots: { default: "operate" }, },
                ],
                tableToolbar: {
                    refresh: {
                        query: () => this.getData(0),
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: "toolbar_buttons",
                    },
                },
                tableData: [],
                tablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: "right",
                    pageSizes: [50, 80],
                    layouts: [
                        "Sizes",
                        "PrevJump",
                        "PrevPage",
                        "JumpNumber",
                        "NextPage",
                        "NextJump",
                        "FullJump",
                        "Total",
                    ],
                    perfect: true,
                    slots: {
                        right: 'current_pageNum'
                    }
                },
                otherFaultShow: false,
                showCreate: false,
                formTitle: '',
                formInfo: {},
                formItems: [
                    { field: 'prjID', title: '项目', span: 24, itemRender: { name: '$select', options: null } },
                ],
                formRules: {
                },
                editIndex: 0,
            }
        },
        async mounted() {
            this.tableLoading = true;
            await this.getAllPrj();
            this.getData(0);
        },
        methods: {
            // 获取所有项目
            getAllPrj() {
                return new Promise((resolve, reject) => {
                    this.positionOption = [];
                    prjAPI.getAllPrj().then(res => {
                        this.formItems[0].itemRender.options = res.map(x => {
                            return { label: x.prjName, value: x.prjID }
                        });
                        this.allPrjList = res.map(x => {
                            return { label: x.prjName, value: x.prjID, customerID: x.customerID }
                        });
                        resolve();
                    }).catch(() => {
                        resolve();
                    });
                });
            },
            
            getTreeList(tree) {
                console.log(tree)
            },
            handleCommand(obj) {
                switch (obj.command) {
                    case 'create': this.createAdd(obj.data.data);
                        break;
                    case 'edit': this.editTree(obj.data.data);
                        break;
                    case 'delete': this.deleteTree(obj.data.data);
                        break;
                }
            },

            nodeClick(node) {
                console.log(node)
            },
            handleNodeClick(node, expanded) {
                console.log(node, expanded)
            },
            handleClose(node) {
                console.log(node)
            },
            createAdd() { },
            editTree() { },
            deleteTree() { },
            divideEquipment() { },
            show() {
                this.otherFaultShow = true;
                this.activeName = '1';
                this.$nextTick(function () {
                    this.$refs.projectTable1.show();
                })
            },
            closeVisible() {
                this.otherFaultShow = false;
                this.activeName = null;
            },
            dialogFormClose() {
                this.showCreate = false;
                this.formInfo = {
                    repOffice: '',
                }
            },
            save() {
                this.tableLoading = true;
                dataExportAPI.createExport().then(res => {
                    this.getData(0)
                }).catch (err => {
                    this.tableLoading = false;
                });
            },

            downloadFile(row) {
                //var data = { name: row.exportID };
                dataExportAPI.downLoadFiles(row.exportID).then(res => {
                    const blob = new Blob([res], { type: 'application/zip;charset=utf-8' });
                    if ('download' in document.createElement('a')) {
                        // 非IE下载
                        const elink = document.createElement('a');
                        elink.download = row.fileName;
                        elink.style.display = 'none';
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href);
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, row.fileName);
                    };
                })
            },
            deleteDe(row) {
                this.$confirm(`确定要删除本条记录吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var index = this.tableData.findIndex(x => x.exportID === row.exportID);
                    var that = this;
                    that.tableLoading = true;
                    dataExportAPI.deleteExport(row.exportID).then((res) => {
                        if (!res) {
                            this.tableLoading = false;
                            this.$message({ type: "warning", message: "删除失败!" });
                        } else {
                            this.tableLoading = false;
                            this.$message({ type: "success", message: "删除成功!" });
                            this.getData();
                        }
                    }).catch(err => {
                        this.tableLoading = false;
                    });
                    setTimeout(function () {
                        that.tableData.splice(index, 1)
                        that.tableLoading = false;
                    }, 500);
                }).catch(() => { });
            },
            getData(type) {
                if (type === 0) {
                    this.tablePage.currentPage = 1;
                };
                var whereStr = " 1 = 1 ";

                if (!!this.searchName) {
                    whereStr += " and fileName like '%" + this.searchName.trim() + "%' ";
                }
                var data = {
                    pageIndex: this.tablePage.currentPage - 1,
                    pageSize: this.tablePage.pageSize,
                    selector: "",
                    where: whereStr,
                    sort: "exportTime",
                    isAsc: false,
                    firstPK: 0,
                    lastPK: 0,
                    isDebugSQL: false,
                };
                this.tableLoading = true;
                dataExportAPI.getAllQuery(data).then(res => {
                    this.tableData = res.result;
                    this.tablePage.total = res.recordCount;
                    this.tableLoading = false;
                }).catch(err => {
                    this.tableLoading = false;
                });
            },
            createProject() {
                this.showCreate = true;
                this.formTitle = '新增';
                this.formInfo = {
                    prjID: '',
                }
            },
            handleClick(event) {
                //this.numName = event.label;
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
            checkboxChange() {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords();
            },
            checkboxAll() {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords(true);
            },

            disabledPlanStartTime({ date }) {
                if (this.formInfo.endTime === '' || !this.formInfo.endTime) {
                    return false;
                } else {
                    return date.getTime() >= new Date(this.formInfo.endTime).getTime();
                }
            },
            disabledPlanEndTime({ date }) {
                if (this.formInfo.startTime === '' || !this.formInfo.startTime) {
                    return false;
                } else {
                    return date.getTime() <= new Date(this.formInfo.startTime).getTime();
                }
            },
            format(ops, op, hasops) {
                var val = null;
                if (hasops) {
                    var options = ops.map(e => {
                        return e.options;
                    }).flat().valueOf();
                    val = options.find(e => e.value === op);
                } else {
                    val = ops.find(e => e.value === op);
                }
                return val ? val.label : '';
            },
        },
        template: "#template"
    }
</script>

<style>
    .tableTxt {
        width: calc(100% + 1px);
        cursor: pointer;
        display: flex;
        align-items: center;
    }

        .tableTxt div {
            width: 0px;
            flex: 1;
            font-weight: 700;
        }

        .tableTxt i {
            font-size: 28px;
            margin-right: 8px;
        }

        .tableTxt svg {
            width: 28px;
            height: 28px;
            margin-right: 8px;
        }

    .tableTxtHoverBlue:hover div {
        color: #2c7ef8;
    }

    .elscrollbar {
        overflow-x: hidden;
    }

    .tableToolbarText {
        font-weight: 600;
        font-size: 14px;
    }

    .tableToolbarTextL {
        margin-left: 8px;
    }

    .elLinkBTN {
        margin: 0 4px;
    }

    .tableToolbar {
        display: flex;
        align-items: center;
    }

    .textHidden {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .modal_footer {
        width: 100%;
        margin: 10px auto;
        display: flex;
        justify-content: flex-end;
    }
</style>